package com.example.goodpet.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Selection;
import android.text.Spannable;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;

import com.example.goodpet.R;
import com.example.goodpet.db.DatabaseHelper;
import com.example.goodpet.db.dao.SearchHistoryDAO;
import com.example.goodpet.db.entity.SearchHistory;
import com.example.goodpet.utils.ActivityManager;
import com.example.goodpet.utils.MyApplication;
import com.example.goodpet.utils.UIUtils;
import com.zackratos.ultimatebarx.ultimatebarx.java.UltimateBarX;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class SearchActivity extends FragmentActivity {

    private String TAG=this.getClass().getSimpleName();
    private ImageView iv_searchBack;
    private Button btn_search;
    private EditText et_searchText;
    private TextView tv_clearHistory;

    private LinearLayout ly_history;
    private String HISTORY="history";
    private String SEARCH_HISTORY="searchHistory";
    private List<SearchHistory> searchHistories=new ArrayList<>();
    private List<String> searchHistoriesContent=new ArrayList<>();

    private int PET=1;
    private int COMMUNITY=2;
    private int USER=3;

    private int TYPE=PET;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        UltimateBarX.statusBarOnly(this)
                .fitWindow(true)
                .colorRes(R.color.ic_back_background)
                .light(true)
                .apply();
        ActivityManager.getInstance().addSearchActivity(this);

        //判断user是否的登录
        isLogin();
        TYPE = getIntent().getIntExtra("type", 1);
        /**
         * 存放搜索历史的sql lite表
         */

        searchHistories = DatabaseHelper.getInstance(this).getSearchHistoryDAO().selectListHistory();
        int count= Math.min(searchHistories.size(), 10);
//        Log.e(TAG, "onCreate: "+count);
        for (int i = 0; i < count; i++) {
//            Log.e(TAG, "onCreate: "+i);
            searchHistoriesContent.add(searchHistories.get(i).getSearchContent());
        }

        initView();
        initListeners();

    }

    private void isLogin() {
        if (MyApplication.user==null)
        startActivityForResult(new Intent(this,LoginActivity.class),100);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (!(requestCode==100 && resultCode==RESULT_OK))ActivityManager.getInstance().removeCurrent();
    }

    /**
     * 获取相对应的控件
     */
    private void initView() {
        iv_searchBack=findViewById(R.id.iv_search_back);
        btn_search=findViewById(R.id.btn_search);
        et_searchText = findViewById(R.id.et_search_text);
        /**
         * 如果是从搜索结果页面跳到该页面，则将原搜索结果的文本内容传进来
         */
        String searchContent = getIntent().getStringExtra("searchContent");
        if(!(null==searchContent)){

            et_searchText.setText(searchContent);
        }

        ly_history=findViewById(R.id.ly_history);
        tv_clearHistory=findViewById(R.id.tv_clear_search);

    }

    /**
     * 实现搜索功能
     */
    private void initListeners() {

        /**
         * 返回服务页面
         */
        iv_searchBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    finish();
            }
        });

        /**
         * 给搜索历史传入空
         */
        ly_history.removeAllViews();
        /**
         * 从数据库中获取搜索历史，并将内容追加到tv_historyText
         */
        if(null!=searchHistoriesContent){

            for (String s : searchHistoriesContent) {
                TextView textView=new TextView(this);
                Resources resources = this.getResources();
                textView.setBackground(resources.getDrawable(R.drawable.btn_round_search_history));
                textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                textView.setPadding(10,10,10,10);
                textView.setTextColor(resources.getColor(R.color.black));
                textView.setGravity(Gravity.CENTER);
                textView.setMaxLines(1);
                textView.setText(s);
                ly_history.addView(textView);
                LinearLayout.LayoutParams lp =  (LinearLayout.LayoutParams) textView.getLayoutParams();
                lp.setMargins(10,10,10,10);
                textView.setLayoutParams(lp);
//                tv_historyText.append(s+" ");
            }
            for (int i = 0; i < ly_history.getChildCount(); i++) {
                TextView childAt = (TextView) ly_history.getChildAt(i);
                childAt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        Log.e(TAG, "onClick: "+childAt.getText().toString() );
                        UIUtils.toast("获取数据库内容",false);
                        Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
                        intent.putExtra("searchContent",childAt.getText().toString());
                        startActivity(intent);

                    }

                });
            }
        }

        /**
         * 监听键盘回车键
         */
        et_searchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //当actionId == XX_SEND 或者 XX_DONE时都触发
                //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN时也触发
                //注意，这是一定要判断event != null。因为在某些输入法上会返回null。
                if ((event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {

                    String trim = et_searchText.getText().toString().trim();
                    if (!trim.isEmpty()) {
                        searchPet(trim);
                        addHistory(trim);
                    }else{
                        Toast.makeText(SearchActivity.this,"搜索内容为空",Toast.LENGTH_SHORT).show();
                    }


                    return true;
                }
                return false;
            }
        });


        /**
         * 搜索按钮的监听
         */
        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String trim = et_searchText.getText().toString().trim();
                /**
                 * 判断搜索框是否为空
                 */
                if(!trim.isEmpty()){
                    /**
                     * 获取数据库中的表，取出搜索框中的首字符放入查询语句进行查询相匹配的内容，并且添加历史搜索记录
                     */

                    searchPet(trim);
                    addHistory(trim);
                }else{
                    Toast.makeText(SearchActivity.this,"搜索内容为空",Toast.LENGTH_SHORT).show();
                }


            }
        });


        tv_clearHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 * 清空数据库中的搜索历史，并更新tv_historyText
                 */
                if(searchHistories.size()>0){
                    DatabaseHelper.getInstance(SearchActivity.this).getSearchHistoryDAO().delete();
                    ly_history.removeAllViews();
                    UIUtils.toast("删除成功",false);
                }else{
                    UIUtils.toast("无历史记录",false);
                }

            }
        });
    }

    private void addHistory(String content) {
        /**
         * 将搜索框内容放入到搜索历史当中去
         */
        TextView textView=new TextView(this);
        Resources resources = this.getResources();
        textView.setBackground(resources.getDrawable(R.drawable.btn_round_search_history));
        textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        textView.setPadding(8,8,8,8);
        textView.setTextColor(resources.getColor(R.color.black));
        textView.setGravity(Gravity.CENTER);
        textView.setText(content);
        /**
         * 如果子控件等于10，则删除最后一个控件，控制空控件数目小于等于10
         */
        Log.e(TAG, "addHistory: "+ly_history.getChildCount());
        if(ly_history.getChildCount()>=10){
            for (int i = ly_history.getChildCount(); i >10 ; i--) {
                ly_history.removeViewAt(i-1);
            }
        }

        ly_history.addView(textView,0);
        LinearLayout.LayoutParams lp =  (LinearLayout.LayoutParams) textView.getLayoutParams();
        lp.setMargins(10,10,10,10);
        textView.setLayoutParams(lp);

        /**
         * 将搜索框内容放入到搜索历史表当中去
         */
        DatabaseHelper.getInstance(this).getSearchHistoryDAO().insert(new SearchHistory(System.currentTimeMillis(),content));
        //UIUtils.toast("添加历史搜索记录成功",false);

    }

    /**
     * 获取数据库中的表，取出搜索框中的首字符放入查询语句进行查询相匹配的内容
     */
    private void searchPet(String content) {
//        UIUtils.toast("获取数据库内容",false);
        Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
        intent.putExtra("searchContent",content);
        intent.putExtra("type",TYPE);
        startActivity(intent);
    }

}
